
//
//  XYChatViewController.m
//  十年少
//
//  Created by 尧的mac on 15/11/28.
//  Copyright © 2015年 xxy.icom. All rights reserved.
//

#import "XYChatViewController.h"

#import "WLKeyBordVIew.h"
#import "AFNetworking.h"
#import "WLMessagesFrame.h"
#import "WLmessagesCell.h"

@interface XYChatViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

/**
 *  创建tableView
 */
@property(nonatomic,weak)UITableView *tableView;

/**
 *  模型数据
 */
@property(nonatomic, strong)NSMutableArray *messagesFrame;
/**
 *  创建WLKeyBordVIew
 */
@property(nonatomic,weak)WLKeyBordVIew *keyBordVIew;
/**
 *  发送的内容
 */
@property(nonatomic, copy)NSString *sendText;
/**
 *  自动回复消息的字典
 */
@property(nonatomic, weak)NSDictionary *autoreply;
/**
 *  键盘是否弹出
 */
@property(nonatomic, assign)BOOL pop;

@end

@implementation XYChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.设置界面数据
    [self setupView];
    
}

#pragma mark -textFiled协议方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    // 1.创建文本输入字符串
    self.sendText = self.keyBordVIew.textField.text;
    [self addMessage:self.sendText type:WLMessagesTypeMe];
    
    textField.text = nil;
    
    // 2.当文本框输入之后就调用请求的聊天回复数据
    [self setupChatData];
    
    return YES;
}


/**
 *  发送一条消息
 */
- (void)addMessage:(NSString *)text type:(WLMessagesType)type
{
    // 2.创建数据模型  和frame模型
    WLMessages *model = [[WLMessages alloc]init];
    
    model.text = text;
    
    model.type = type;
    
    WLMessagesFrame *wmsF = [[WLMessagesFrame alloc]init];
    wmsF.messages = model;
    
    [self.messagesFrame addObject:wmsF];
    
    // 3.重新加载数据
    [self.tableView reloadData];
    
    // 4.自动滚动表格到最后一行
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:self.messagesFrame.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    
}

#pragma mark -加载聊天数据
- (void)setupChatData
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    mgr.responseSerializer  = [AFHTTPResponseSerializer serializer];
    [mgr.requestSerializer setValue:@"e2c382ce8849e756b2847a79e2cfb8a0" forHTTPHeaderField:@"apikey"];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"key"] = @"879a6cb3afb84dbf4fc84a1df2ab7319";
#warning  必须把得到的输入框的值转化一下才能作为字典的值，才能得到请求
    NSString *info = [NSString stringWithString:self.sendText];
    params[@"info"] = info;
    params[@"userid"] = @"eb2edb736";
    [mgr GET:@"http://apis.baidu.com/turing/turing/turing" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        [self addMessage:dict[@"showtext"] type:WLMessagesTypeOther];
    
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //        NSLog(@"%@", error);
    }];
    
    
}
#pragma mark -加载界面数据
- (void)setupView
{
    // 设置聊天控制器的背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    // 设置标题
    self.title = @"快来聊天";
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-44-20)];
    //代理为viewController
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    
    // 导入界面
    WLKeyBordVIew *keyBordVIew = [[WLKeyBordVIew alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame) - 44, CGRectGetWidth(self.view.frame), 44)];
    [self.view addSubview:keyBordVIew];
    self.keyBordVIew = keyBordVIew;
    keyBordVIew.textField.text = self.sendText;
    
//     输入框
    keyBordVIew.textField.delegate = self;
    
    // 去除分割线
    self.tableView.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    //监听键盘通知(有addObserve就有dealloc)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messagesFrame.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WLmessagesCell *cell = [WLmessagesCell cellWithTableView:tableView];
    
    //给cell传递模型
    cell.messagesFrame = self.messagesFrame[indexPath.row];
    return cell;
}

#pragma mark -设置cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取得该行的cell高度
    WLMessagesFrame *mf = self.messagesFrame[indexPath.row];
    return mf.cellHeight;
}

#pragma mark -加载模型数据
-(NSMutableArray *)messagesFrame
{
    //进行懒加载
    if (_messagesFrame == nil) {
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"messages.plist" ofType:nil]];
        
        NSMutableArray *messageArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            //消息模型
            WLMessages *mes = [WLMessages messagesWithDict:dict];
            
            WLMessagesFrame *messagesFrame = [[WLMessagesFrame alloc]init];
            messagesFrame.messages = mes;
            
            [messageArray addObject:messagesFrame];
        }
        _messagesFrame = messageArray;
    }
    return _messagesFrame;
}
#pragma mark -键盘的退出
/**
 *  滚动键盘退出(开始抓取tableView时候退出键盘)
 */
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark -消息中心取消监听事件
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

#pragma mark -监听键盘frame改变的方法
-(void)keyboardChangeFrame:(NSNotification *)sender
{
    // 设置窗口的颜色
    self.view.window.backgroundColor = self.tableView.backgroundColor;
    
    // 0.取出键盘动画的时间
    CGFloat duration = [sender.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 1.取得键盘最后的frame
    CGRect keyboardFrame = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2.计算控制器的view需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    
    self.pop = !self.pop;
    if (self.pop) {
        
        self.tableView.frame = CGRectMake(0, 20-transformY, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-44-20+transformY);
        
    }else{
        self.tableView.frame = CGRectMake(0, 20, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-44-20);
    }
    //    [self.tableView reloadData];
    //transform是相对位移
    //    self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    
    // 3.执行动画（self.view.transform是tableView加上textFiled一起向上移动，也就是整个view）
    [UIView animateWithDuration:duration animations:^{
        
        self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
    
    //    3.让UITableView的最后一个cell滚到键盘最上面
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.messagesFrame.count - 1 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    //    NSLog(@"%f",transformY);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


